<?php

/**
 * Control panel for administering the module settings
 * 
 * Provides the following functionality:
 * 
 * - Add/edit/delete meeting rooms
 * - Add/delete meeting room locations (i.e. buildings/offices)
 * - Change booking granularity
 * - Change maximum advance booking days
 * 
 * Should be fairly straightforward, only thing really worth mentioning is the 
 * 'boolean room attributes'. For example, there is currently one of these which 
 * is has_video_conferencing i.e. does the meeting room have video conferencing 
 * facilities. You can add further attributes by adding to the array 
 * $boolean_room_attributes. If you install the module from scratch this will 
 * be fine because the database table exp_ncb_rooms will have fields for the attributes. 
 * If you have already installed the module, you can uninstall and reinstall - 
 * if you don't want to lose any data you'll need to alter the table manually. 
 * At some point the control panel class could be tweaked to do an integrity 
 * check every time it runs and alter the table if necessary. Alternatively an 
 * extra form could be provided for adding room attributes. Once you've added 
 * an attribute, you must put an entry in the language file corresponding to 
 * the database field name you chose, this will be used to display the 
 * attribute on the meeting rooms table output in the end-user UI.
 * 
 *
 **/
class Ncb_rooms_CP
{
	const DEFAULT_MAX_ADVANCE_BOOKING = 14; // (days)
	const DEFAULT_BOOKING_GRANULARITY = 30; // (minutes);

	var $version = '2.00';
	var $module_name = 'NCB Room Bookings';
	var $view_limit = 20;
	
	var $boolean_room_attributes = array(); // Used to set up tick boxes for room attributes e.g. 
											//
	                                        // "[x] Has video conferencing facilities?"
											//
											// array(<form/database variable name> => 
										    //         array('long' => '<long label text>', 
											//               'short' => '<short label text>'),
										    //       ...
	
    // -------------------------
    //  Constructor
    // -------------------------
    
    function Ncb_rooms_CP( $switch = TRUE )
    {
        global $IN, $LANG;
        
		/* initialise extra room attributes */	
		$this->boolean_room_attributes = array(
			'has_video_conferencing' => array('long' => $LANG->line('has_video_conferencing'),
											  'short' => $LANG->line('video'))
		);
		
        if (isset($IN) && $switch)
        {
            switch($IN->GBL('P'))
            {
                 case 'view_rooms'      :	$this->view_rooms();
                     break;	
                 case 'delete_room'     :	$this->delete_room();
                     break;
                 case 'add_rooms'       :	$this->modify_room();
                     break;
                 case 'modify_room'     :	$this->modify_room();
                     break;
                 case 'update_room'     :	$this->update_room();
                     break;
                 case 'view_locations'      :	$this->view_locations();
                     break;	
                 case 'delete_location'     :	$this->delete_location();
                     break;
                 case 'add_locations'       :	$this->modify_location();
                     break;
                 case 'modify_location'     :	$this->modify_location();
                     break;
                 case 'update_location'     :	$this->update_location();
                     break;
                 case 'update_settings'     :	$this->update_settings();
                     break;
                 default                :	$this->ncb_rooms_home();
                     break;
            }
        }
    }
    // END

    // ----------------------------------------
    //  Module installer
    // ----------------------------------------

    function ncb_rooms_module_install()
    {
        global $DB;        
        
		$mod_class_name = str_replace("_CP", "", get_class($this));
		
		// module DB info
 
        $sql[] = "INSERT INTO exp_modules (module_id, 
                                           module_name, 
                                           module_version, 
                                           has_cp_backend) 
                                           VALUES 
                                           ('', 
                                           '$mod_class_name', 
                                           '$this->version', 
                                           'y')";
		// rooms table
        $rooms_table_sql = 
			"CREATE TABLE IF NOT EXISTS `exp_ncb_rooms` (
			                 `room_id` INT(6) UNSIGNED NOT NULL AUTO_INCREMENT,
			                 `room_name` CHAR(255) NOT NULL ,
			                 `room_description` TEXT NOT NULL ,
			                 `room_size` enum('small', 'medium', 'large') DEFAULT 'small',
							 `location_idFK` int(6) NOT NULL DEFAULT -1,
							 `sort_order` int DEFAULT 0,
			                 `hex_colour` CHAR(8) DEFAULT '',
							 `has_video_conferencing` enum('yes','no') default 'no',
							 `extension` varchar(4) default NULL,
							 `login` varchar(20) default NULL,
							 `password` varchar(10) default NULL,
							 PRIMARY KEY  (`room_id`)
			";
		
		/*
		 	Create fields for each of the room attributes
		*/
		if (sizeof($this->boolean_room_attributes)) 
		{
			foreach ($this->boolean_room_attributes as $field_name => $properties)
			{
				$rooms_table_sql .=  ", `$field_name` enum('yes', 'no') DEFAULT 'no'\n";			
			}    
		}							
							
		$rooms_table_sql .= ", PRIMARY KEY (`room_id`));";		                 
				                           
        $sql[] = $rooms_table_sql;
    
		// locations table - e.g. Mocatta House
        $sql[] = "CREATE TABLE IF NOT EXISTS `exp_ncb_room_locations` (
                 `location_id` INT(6) UNSIGNED NOT NULL AUTO_INCREMENT,
                 `location_name` CHAR(255) NOT NULL ,
                 PRIMARY KEY (`location_id`));";

		// bookings table
        $sql[] = "CREATE TABLE IF NOT EXISTS `exp_ncb_room_bookings` (
                 `room_booking_id` INT(6) UNSIGNED NOT NULL AUTO_INCREMENT,
                 `room_idFK` INT(6) NOT NULL ,
                 `user_idFK` INT(6) NOT NULL ,
                 `start_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00' ,
				 `end_time` DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',				 
                 `activity_name` CHAR(255) NOT NULL ,
                 PRIMARY KEY (`room_booking_id`));";

		// module settings
        $sql[] = "CREATE TABLE IF NOT EXISTS `exp_ncb_rooms_settings` (
                 `setting_id` INT(6) UNSIGNED NOT NULL AUTO_INCREMENT,
                 `max_advance_booking_days` INT NOT NULL DEFAULT ".self::DEFAULT_MAX_ADVANCE_BOOKING.",
                 `booking_granularity` INT NOT NULL DEFAULT ".self::DEFAULT_BOOKING_GRANULARITY.",
                 PRIMARY KEY (`setting_id`));";

		$sql[] = "INSERT INTO exp_ncb_rooms_settings VALUES()"; // insert empty row				 
	
				
		// static data
		$sql[] = "INSERT INTO exp_ncb_room_locations (location_id, location_name) VALUES ('1', 'Mocatta House')";
		$sql[] = "INSERT INTO exp_ncb_room_locations (location_id, location_name) VALUES ('2', 'Lanchester House')";
	
		
		$sql[] = "INSERT INTO exp_ncb_rooms (room_id, room_name, room_description, room_size, location_idFK, sort_order, hex_colour, has_video_conferencing) VALUES ('1', 'Piers Webster', 'The large conference room.', 'large', '1', '1', '#ff7f00', 'yes')";
		$sql[] = "INSERT INTO exp_ncb_rooms (room_id, room_name, room_description, room_size, location_idFK, sort_order, hex_colour, has_video_conferencing) VALUES ('11', 'Talking Island', 'In Lanchester North', 'medium', '2', '9', '#ff002a', 'no')";
		$sql[] = "INSERT INTO exp_ncb_rooms (room_id, room_name, room_description, room_size, location_idFK, sort_order, hex_colour, has_video_conferencing) VALUES ('3', 'Ascalon', 'The one with purple furniture', 'medium', '1', '2', '#fcff00', 'no')";
		$sql[] = "INSERT INTO exp_ncb_rooms (room_id, room_name, room_description, room_size, location_idFK, sort_order, hex_colour, has_video_conferencing) VALUES ('4', 'Atlas Park', 'The really big room', 'large', '2', '3', '#ffd67c', 'yes')";
		$sql[] = "INSERT INTO exp_ncb_rooms (room_id, room_name, room_description, room_size, location_idFK, sort_order, hex_colour, has_video_conferencing) VALUES ('5', 'Cantha', 'The one at the end near the vending machine', 'small', '2', '4', '#133c92', 'no')";
		$sql[] = "INSERT INTO exp_ncb_rooms (room_id, room_name, room_description, room_size, location_idFK, sort_order, hex_colour, has_video_conferencing) VALUES ('6', 'Grandville', 'The one second from the end near the vending machine', 'small', '2', '5', '#ff017d', 'no')";
		$sql[] = "INSERT INTO exp_ncb_rooms (room_id, room_name, room_description, room_size, location_idFK, sort_order, hex_colour, has_video_conferencing) VALUES ('7', 'Aden', '', 'medium', '2', '6', '#a7ff00', 'no')";
		$sql[] = "INSERT INTO exp_ncb_rooms (room_id, room_name, room_description, room_size, location_idFK, sort_order, hex_colour, has_video_conferencing) VALUES ('8', 'Elona', 'The one near the Live Ops team, next to Lanchester North Kitchen', 'small', '2', '7', '#3e2e89', 'no')";
		$sql[] = "INSERT INTO exp_ncb_rooms (room_id, room_name, room_description, room_size, location_idFK, sort_order, hex_colour, has_video_conferencing) VALUES ('10', 'Pocket D', 'The northernmost room in Lanchester North', 'small', '2', '8', '#6fb4ec', 'no')";

        foreach ($sql as $query)
        {
            $DB->query($query);
        }
        
        return true;
    }
    // END

    // ----------------------------------------
    //  Module de-installer
    // ----------------------------------------

    function ncb_rooms_module_deinstall()
    {
        global $DB;    

		$mod_class_name = preg_replace("'_CP$'", "", get_class($this));
		
        $query = $DB->query("SELECT module_id
                             FROM exp_modules 
                             WHERE module_name = '$mod_class_name'"); 
                
        $sql[] = "DELETE FROM exp_module_member_groups 
                  WHERE module_id = '".$query->row['module_id']."'";      
                  
        $sql[] = "DELETE FROM exp_modules 
                  WHERE module_name = '$mod_class_name'";
                  
        $sql[] = "DELETE FROM exp_actions 
                  WHERE class = '".get_class($this)."'";
                                    
        $sql[] = "DROP TABLE IF EXISTS exp_ncb_rooms";

        $sql[] = "DROP TABLE IF EXISTS exp_ncb_room_locations";

        $sql[] = "DROP TABLE IF EXISTS exp_ncb_room_bookings";

        $sql[] = "DROP TABLE IF EXISTS exp_ncb_rooms_settings";

        foreach ($sql as $query)
        {
            $DB->query($query);
        }

        return true;
    }
    // END
	

    // ----------------------------------------
    //  Module Homepage
    // ----------------------------------------

    function ncb_rooms_home($msg="", $msg_class="success")
    {
        global $DSP, $LANG;
                        
        $DSP->title = $LANG->line('ncb_rooms_module_name');
        $DSP->crumb = $DSP->anchor(BASE.
                                   AMP.'C=modules'.
                                   AMP.'M=ncb_rooms',
                                   $LANG->line('ncb_rooms_module_name'));        							

        $DSP->crumb .= $DSP->crumb_item($LANG->line('rooms_menu'));    

        if ($msg != '') 
        { 
			if ($msg_class == 'error') 
			{
            	$DSP->body .= $DSP->error_message($msg).BR.BR; 							    
			}
			else
			{
            	$DSP->body .= $DSP->qdiv($msg_class, $msg).BR.BR; 				
			}
        } 

        
//        $DSP->body .= $DSP->heading($LANG->line('rooms_menu'));   
//		$DSP->body .= $DSP->br();
		
		$this->view_rooms();																		   													   
/*        
        $DSP->body .= $DSP->qdiv('itemWrapper', $DSP->heading($DSP->anchor(BASE.
                                                                           AMP.'C=modules'.
                                                                           AMP.'M=ncb_rooms'.
                                                                           AMP.'P=add_rooms', 
                                                                           $LANG->line('add_room')),
                                                                           5));
*/
/*																		   
        $DSP->body .= $DSP->qdiv('itemWrapper', $DSP->heading($DSP->anchor(BASE.
                                                                           AMP.'C=modules'.
                                                                           AMP.'M=ncb_rooms'.
                                                                           AMP.'P=view_rooms', 
                                                                           $LANG->line('view_rooms')),
                                                                           5));
*/

		$DSP->body .= BR . "<hr />" . BR;
		$this->view_locations();

		$DSP->body .= BR . "<hr />" . BR;
		$this->modify_settings();
    }
    // END

	
    // ------------------------- 
    //  Add/Modify Settings Form 
    // ------------------------- 
     
    function modify_settings($msg='') 
    { 
        global $DSP, $LANG, $DB, $IN; 
         
        // ------------------------------------------------------- 
        //  Retrieve data
        // ------------------------------------------------------- 
         
		$sql = "SELECT * FROM exp_ncb_rooms_settings";
	    $query = $DB->query($sql); 
	                               
//		print("query: $sql<br/>");//TMP
//		print_r($query->row);
							 	           
	    $max_advance_booking_days = $query->row['max_advance_booking_days']; 
        $max_advance_booking_days = (empty($max_advance_booking_days) ? self::DEFAULT_MAX_ADVANCE_BOOKING : $max_advance_booking_days);

	    $booking_granularity = $query->row['booking_granularity']; 
        $booking_granularity = (empty($booking_granularity) ? self::DEFAULT_BOOKING_GRANULARITY : $booking_granularity);

		 
        $r = $DSP->heading($LANG->line('settings')); 
		$r .= BR;
         
        if ($msg != '') 
        { 
            $r .= $DSP->qdiv('success', $msg).BR; 
        } 
         
        // ------------------------------------------------------- 
        // Declare Form 
        // ------------------------------------------------------- 
         
        $r .= $DSP->form('C=modules'.AMP.'M=ncb_rooms'.AMP.'P=update_settings', 'target'); 
         
         
        // ------------------------------------------------------- 
        //  Table For fields
        // ------------------------------------------------------- 
         
        $r .= $DSP->table('tableBorder', '0', '0', '400');

        $r .= $DSP->tr();                
        $r .= $DSP->table_qcell('tableCellOne', $DSP->qspan('', $LANG->line('advance_booking')));

		$days_options = '';

		for ($i = 1; $i <= 60; $i++)
		{
			$selected = ($max_advance_booking_days == $i ? 'selected' : '');
			$days_options .= $DSP->input_select_option($i, $i, $selected);			    
		}
				
        $r .= $DSP->table_qcell('tableCellTwo',   $DSP->input_select_header('max_advance_booking_days')
												  .$days_options
									              .$DSP->input_select_footer()
												  ." ".$LANG->line('days')
								);                


//        $r .= $DSP->table_qcell('tableCellTwo', $DSP->input_text('max_advance_booking_days', $max_advance_booking_days, 2, 2, 'textfield', '')
//												."" . $LANG->line('days') . "");                
        $r .= $DSP->tr_c();

        $r .= $DSP->tr();                
        $r .= $DSP->table_qcell('tableCellOne', $DSP->qspan('', $LANG->line('booking_granularity')));


		$granularity_options = '';
		
		for ($i = 1; $i <= 60; $i++)
		{
			if (60 % $i == 0) 
			{
				$selected = ($booking_granularity == $i ? 'selected' : '');
				$granularity_options .= $DSP->input_select_option($i, $i, $selected);			    
			}
		}
		
		
        $r .= $DSP->table_qcell('tableCellTwo',   $DSP->input_select_header('booking_granularity')
												  .$granularity_options
									              .$DSP->input_select_footer()
												  ." ".$LANG->line('minutes')
								);                
												  
//        $r .= $DSP->table_qcell('tableCellTwo', $DSP->input_text('booking_granularity', $booking_granularity, 2, 2, 'textfield', '')
//												."" . $LANG->line('minutes') . "");                
        $r .= $DSP->tr_c();

        $r .= $DSP->table_c();       

        // ------------------------------------------------------- 
        //  Submit Button Text - Update 
        // ------------------------------------------------------- 
         
        $r .= $DSP->qdiv('itemWrapper', BR.$DSP->input_submit($LANG->line('update_settings')));     
         
        // ------------------------------------------------------- 
        //  Close Form 
        // ------------------------------------------------------- 
         
        $r .= $DSP->form_c(); 

        $DSP->body .= $r;   
    } 
    // END modify_setting
	
    // ------------------------- 
    // Update settings
    // ------------------------- 
     
	/**
	 * Validate and make changes to module settings
	 */ 
    function update_settings() 
    { 
        global $LANG, $DB, $IN, $DSP; 
                   
//		print_r($_POST);//TMP

        $max_advance_booking_days = $_POST['max_advance_booking_days'];
		$booking_granularity = $_POST['booking_granularity'];

		$result = '';
		$is_valid_submission = TRUE;

		if (!is_numeric($max_advance_booking_days) || $max_advance_booking_days < 1) 
		{
			$result .= $LANG->line('non_integer_error') ." <strong>". $LANG->line('advance_booking') . "</strong>";
			$result .= BR;
			$is_valid_submission = FALSE;
		}
				         
		if (!is_numeric($booking_granularity) || $booking_granularity < 1) 
		{
			$result .= $LANG->line('non_integer_error') ." <strong>". $LANG->line('booking_granularity') . "</strong>";
			$result .= BR;
			$is_valid_submission = FALSE;
		}
		
		$message_class = 'success';
		
		if ($is_valid_submission) 
		{
	        $data = array('max_advance_booking_days' => $max_advance_booking_days,
						  'booking_granularity' => $booking_granularity); 
	                  
	        $DB->query($DB->update_string('exp_ncb_rooms_settings', $data, '1=1')); 		    
			
			$result = $LANG->line('settings_updated');
		}
		else
		{
			$message_class = 'error';
		}

        // --------------------------------------------------- 
        //  Return to main menu with result message 
        // --------------------------------------------------- 
		
        return $this->ncb_rooms_home($result, $message_class);          
    } 
    // END update_setting

    // ------------------------- 
    //  View Rooms 
    // ------------------------- 
     
    function view_rooms($msg='') 
    { 
        global $DSP, $LANG, $DB, $FNS; 
      
	     
        // ------------------------------------------------------- 
        //  Select All Rooms from Database 
        // ------------------------------------------------------- 
         
        $query = $DB->query("SELECT * FROM exp_ncb_rooms LEFT JOIN exp_ncb_room_locations ON location_idFK = location_id ORDER BY sort_order"); 
                                 
        if ($query->num_rows == 0) 
        { 
//            $DSP->body .= $DSP->error_message($LANG->line('no_rooms'));         
            $DSP->body .= $DSP->qdiv("itemWrapper", $LANG->line('no_rooms'));         
//            return; 
        } 
		else
		{	         
	        // ------------------------------------------------------- 
	        //  Page Heading and Success Message, if any 
	        // ------------------------------------------------------- 
	         
			$r = '';
			 
	        if ($msg != '') 
	        { 
	            $r .= $DSP->qdiv('success', $msg).BR.BR; 				
	        } 
	            
	        $r .= $DSP->heading($LANG->line('current_rooms')); 
			$r .= BR;

	        $r .= $DSP->qdiv('', "<em>" . $LANG->line('rooms_info'). "</em>"); 
			$r .= BR;
	         
	        // ------------------------------------------------------- 
	        //  Table and Table Headers 
	        // ------------------------------------------------------- 
	         
	        $r .= $DSP->table('tableBorder', '0', '0', ''). 
	              $DSP->tr(). 
	              $DSP->td('tablePad'); 
	               
			$column_headings = 	array( 
                                    $LANG->line('sort_order')."&nbsp;", 
                                    $LANG->line('colour')."&nbsp;", 
                                    $LANG->line('name'), 
                                    $LANG->line('description'), 
                                    $LANG->line('size'), 
                                    $LANG->line('location'), 
                                 ); 			
								 
			if (sizeof($this->boolean_room_attributes) > 0) 
			{
				foreach ($this->boolean_room_attributes as $field_name => $properties)
				{
					$column_headings[] = $properties['short'];
				}
			}
			
			$column_headings[] = '&nbsp;'; // modify
			$column_headings[] = '&nbsp;'; // delete
			
	        $r .= $DSP->table('', '0', '', ''). 
	              $DSP->tr(). 
	              $DSP->table_qcell('tableHeadingBold', $column_headings). 
	              $DSP->tr_c(); 
	
	        $i = 0; 
	         
	        // ------------------------------------------------------- 
	        //  Display Rows of Rooms 
	        // ------------------------------------------------------- 
	         
	        foreach($query->result as $row) 
	        { 
//				print_r($row);//TMP
			
	            $style = ($i++ % 2) ? 'tableCellOne' : 'tableCellTwo'; 
	                       
	            $r .= $DSP->tr(); 
	
				$hex_colour = $row['hex_colour'];				
				$colour_html = "<span style=\"background-color: $hex_colour\">$hex_colour</span>";
	
	            $r .= $DSP->table_qcell($style, $row['sort_order'],'','top'); 
	            $r .= $DSP->table_qcell($style, $colour_html,'','top'); 
	            $r .= $DSP->table_qcell($style, $FNS->word_limiter($row['room_name'],$this->view_limit),'','top'); 
	            $r .= $DSP->table_qcell($style, $FNS->word_limiter($row['room_description'],$this->view_limit),'','top'); 
	            $r .= $DSP->table_qcell($style, $FNS->word_limiter($row['room_size'],$this->view_limit),'','top'); 
	            $r .= $DSP->table_qcell($style, $row['location_name'],'','top'); 
				
				if (sizeof($this->boolean_room_attributes) > 0) 
				{
					foreach ($this->boolean_room_attributes as $field_name => $properties)
					{
	            		$r .= $DSP->table_qcell($style, $row[$field_name],'','top'); 
					}
				}
					             
	            $r .= $DSP->table_qcell($style, $DSP->anchor(BASE. 
	                                                          AMP.'C=modules'. 
	                                                          AMP.'M=ncb_rooms'. 
	                                                          AMP.'P=modify_room'. 
	                                                          AMP.'room_id='. 
	                                                          $row['room_id'], 
	                                                          $LANG->line('modify')),'','top'); 
	                                                           
	            $r .= $DSP->table_qcell($style, $DSP->anchor(BASE. 
	                                                          AMP.'C=modules'. 
	                                                          AMP.'M=ncb_rooms'. 
	                                                          AMP.'P=delete_room'. 
	                                                          AMP.'room_id='. 
	                                                          $row['room_id'], 
	                                                          $LANG->line('delete')),'','top'); 
	                                                           
	            $r .= $DSP->tr_c(); 
	             
	        } 
	         
	        // ------------------------------------------------------- 
	        //  Close Table and Output to $DSP->body 
	        // ------------------------------------------------------- 
	
	        $r .= $DSP->table_c(); 
	
	        $r .= $DSP->td_c()    
	             .$DSP->tr_c()       
	             .$DSP->table_c(); 
	         
	        $DSP->body .= $r; 
		}         

		$DSP->body .= $DSP->br();
        $DSP->body .= $DSP->qdiv('itemWrapper', $DSP->heading($DSP->anchor(BASE.
                                                                           AMP.'C=modules'.
                                                                           AMP.'M=ncb_rooms'.
                                                                           AMP.'P=add_rooms', 
                                                                           $LANG->line('add_room')),
                                                                           5));
     } 
     // END view_rooms


    // ------------------------- 
    //  View Locations 
    // ------------------------- 
     
    function view_locations($msg='') 
    { 
        global $DSP, $LANG, $DB, $FNS; 
         
        // ------------------------------------------------------- 
        //  Select All Locations from Database 
        // ------------------------------------------------------- 
         
        $query = $DB->query("SELECT * FROM exp_ncb_room_locations"); 
                                 
        if ($query->num_rows == 0) 
        { 
//            $DSP->body .= $DSP->error_message($LANG->line('no_locations'));         
            $DSP->body .= $DSP->qdiv("itemWrapper", $LANG->line('no_locations'));         
//            return; 
        } 
		else
		{	         
	        // ------------------------------------------------------- 
	        //  Page Heading and Success Message, if any 
	        // ------------------------------------------------------- 
	         
			$r = '';
			 
	        if ($msg != '') 
	        { 
	            $r .= $DSP->qdiv('success', $msg).BR.BR; 				
	        } 
	            
	        $r .= $DSP->heading($LANG->line('current_locations')); 
			$r .= BR;
	         
	        // ------------------------------------------------------- 
	        //  Table and Table Headers 
	        // ------------------------------------------------------- 
	         
	        $r .= $DSP->table('tableBorder', '0', '0', ''). 
	              $DSP->tr(). 
	              $DSP->td('tablePad'); 
	               
	        $r .= $DSP->table('', '0', '', ''). 
	              $DSP->tr(). 
	              $DSP->table_qcell('tableHeadingBold', 
	                                array( 
	                                        $LANG->line('name'), 
	                                        '&nbsp;', 
	                                        '&nbsp;', 
	                                     ) 
	                                ). 
	              $DSP->tr_c(); 
	
	        $i = 0; 
	         
	        // ------------------------------------------------------- 
	        //  Display Rows of Locations 
	        // ------------------------------------------------------- 
	         
	        foreach($query->result as $row) 
	        { 
//				print_r($row);//TMP
			
	            $style = ($i++ % 2) ? 'tableCellOne' : 'tableCellTwo'; 
	                       
	            $r .= $DSP->tr(); 
	
	            $r .= $DSP->table_qcell($style, $FNS->word_limiter($row['location_name'],$this->view_limit),'','top'); 
	             
	            $r .= $DSP->table_qcell($style, $DSP->anchor(BASE. 
	                                                          AMP.'C=modules'. 
	                                                          AMP.'M=ncb_rooms'. 
	                                                          AMP.'P=modify_location'. 
	                                                          AMP.'location_id='. 
	                                                          $row['location_id'], 
	                                                          $LANG->line('modify')),'','top'); 
	                                                           
	            $r .= $DSP->table_qcell($style, $DSP->anchor(BASE. 
	                                                          AMP.'C=modules'. 
	                                                          AMP.'M=ncb_rooms'. 
	                                                          AMP.'P=delete_location'. 
	                                                          AMP.'location_id='. 
	                                                          $row['location_id'], 
	                                                          $LANG->line('delete')),'','top'); 
	                                                           
	            $r .= $DSP->tr_c(); 
	             
	        } 
	         
	        // ------------------------------------------------------- 
	        //  Close Table and Output to $DSP->body 
	        // ------------------------------------------------------- 
	
	        $r .= $DSP->table_c(); 
	
	        $r .= $DSP->td_c()    
	             .$DSP->tr_c()       
	             .$DSP->table_c(); 
	         
	        $DSP->body .= $r; 
		}         

		$DSP->body .= $DSP->br();
        $DSP->body .= $DSP->qdiv('itemWrapper', $DSP->heading($DSP->anchor(BASE.
                                                                           AMP.'C=modules'.
                                                                           AMP.'M=ncb_rooms'.
                                                                           AMP.'P=add_locations', 
                                                                           $LANG->line('add_location')),
                                                                           5));
     } 
     // END view_locations

     
    // ------------------------- 
    //  Add/Modify Room Form 
    // ------------------------- 
     
    function modify_room($msg='') 
    { 
        global $DSP, $LANG, $DB, $IN; 
         
        // ------------------------------------------------------- 
        //  If Modfying Existing Room, Retrieve data
        // ------------------------------------------------------- 
		$boolean_room_values = array();
        $query = '';
		 
        if ( ! $IN->GBL('room_id')) 
        { 
            $room_name = ''; 
            $room_description = '';
            $room_size = ''; 
            $room_location = ''; 
			$sort_order = '';
//			$has_video_conferencing = '';
        } 
        else 
        { 
			$sql = "SELECT * FROM exp_ncb_rooms LEFT JOIN exp_ncb_room_locations ON location_id = location_idFK WHERE room_id = '".$IN->GBL('room_id')."'";
            $query = $DB->query($sql); 
                                 
//			print("query: $sql<br/>");//TMP
								 
            if ($query->num_rows == 0) 
            { 
                $DSP->body .= $DSP->error_message($LANG->line('invalid_room_id'));         
                return; 
            } 
             
            $room_name = $query->row['room_name']; 
            $room_description = $query->row['room_description'];
            $room_size = $query->row['room_size']; 
            $room_location = $query->row['location_idFK']; 
            $sort_order = $query->row['sort_order']; 
            $hex_colour = $query->row['hex_colour']; 
//			$has_video_conferencing = $query->row['has_video_conferencing']; 			
       } 

		if (sizeof($this->boolean_room_attributes) > 0) 
		{
			foreach ($this->boolean_room_attributes as $field_name => $properties)
			{
				if ($query)
					$boolean_room_values[$field_name] = $query->row[$field_name];
				else
					$boolean_room_values[$field_name] = "";
			}
		}
         
		// get location options for rooms
		$location_options = '';
		$query = $DB->query("SELECT * FROM exp_ncb_room_locations"); 
		
		if ($query->num_rows > 0) 
		{				
			foreach($query->result as $row) 
			{ 
				$selected = ($row['location_id'] == $room_location ? 'selected' : '');
//				print("location id: ".$row['location_id']." room location: $room_location<br/>");//TMP
				$location_options .= $DSP->input_select_option($row['location_id'], $row['location_name'], $selected);
			} 
		
//			print("location options:<br/> ".htmlspecialchars($location_options));//TMP
		}
		else
		{
			print("no locations<br/>");//TMP
		}

        // ------------------------------------------------------- 
        //  HTML Title and Navigation Crumblinks 
        // ------------------------------------------------------- 
         
        $DSP->title = $LANG->line('ncb_rooms_module_name'); 
        $DSP->crumb = $DSP->anchor(BASE. 
                                   AMP.'C=modules'. 
                                   AMP.'M=ncb_rooms', 
                                   $LANG->line('ncb_rooms_module_name'));        
                                    
        $DSP->crumb .= $DSP->crumb_item(($room_name != '') ? $LANG->line('update_room') : $LANG->line('add_room')); 
         
         
        // ------------------------------------------------------- 
        //  Page Heading and Success Message, if any 
        // ------------------------------------------------------- 
         
        $r = $DSP->heading(($room_name != '') ? $LANG->line('update_room') : $LANG->line('add_room')); 
         
        if ($msg != '') 
        { 
            $r .= $DSP->qdiv('success', $msg).BR; 
        } 
         
        // ------------------------------------------------------- 
        // Declare Form 
        // ------------------------------------------------------- 
         
        $r .= $DSP->form('C=modules'.AMP.'M=ncb_rooms'.AMP.'P=update_room', 'target'); 
         
        // ------------------------------------------------------- 
        //  Modifying Existing Room, Hidden Form Field for ID 
        // ------------------------------------------------------- 
         
        if ($room_name != '') 
        { 
            $r .= $DSP->input_hidden('room_id', $IN->GBL('room_id')); 
        } 
         
        // ------------------------------------------------------- 
        //  Table For Textarea 
        // ------------------------------------------------------- 
         
        $r .= $DSP->table('tableBorder', '0', '0', '400');

        $r .= $DSP->tr();                
        $r .= $DSP->table_qcell('tableCellOne', $DSP->qspan('', $LANG->line('room_name')));
        $r .= $DSP->table_qcell('tableCellTwo', $DSP->input_text('room_name', $room_name, 50, 200, 'textfield', '300'));                
        $r .= $DSP->tr_c();

        $r .= $DSP->tr();                
        $r .= $DSP->table_qcell('tableCellOne', $DSP->qspan('', $LANG->line('room_description')), '', 'top');
        $r .= $DSP->table_qcell('tableCellTwo', $DSP->input_textarea('room_description', $room_description, 3, 'textarea', '300'));                
        $r .= $DSP->tr_c();

        $r .= $DSP->tr();                
        $r .= $DSP->table_qcell('tableCellOne', $DSP->qspan('', $LANG->line('room_size')));

		$size_options = '';
		$sizes = array('small', 'medium', 'large');
		foreach ($sizes as $size)
		{
			$selected = ($room_size == $size ? 'selected' : '');
			$size_options .= $DSP->input_select_option($size, $LANG->line($size), $selected);
		}
		
        $r .= $DSP->table_qcell('tableCellTwo',   $DSP->input_select_header('room_size')
												  .$size_options
									              .$DSP->input_select_footer());                
        $r .= $DSP->tr_c();

        $r .= $DSP->tr();                
        $r .= $DSP->table_qcell('tableCellOne', $DSP->qspan('', $LANG->line('room_location')));

        $r .= $DSP->table_qcell('tableCellTwo',   $DSP->input_select_header('room_location')
												  .$location_options
									              .$DSP->input_select_footer());                
        $r .= $DSP->tr_c();
		
		$is_adding_room = ($_REQUEST['P'] == 'add_rooms');
		$rooms_count = $this->get_rooms_count();	
		$max = ($is_adding_room ? $rooms_count + 1 : $rooms_count);
			
		$order_options = '';
		for ($i = 1; $i <= $max; $i++)
		{
			if ($is_adding_room)
				$selected = ($max == $i ? 'selected' : '');	
			else
				$selected = ($sort_order == $i ? 'selected' : '');
				
			$order_options .= $DSP->input_select_option($i, $i, $selected);    
		}

        $r .= $DSP->tr();                
        $r .= $DSP->table_qcell('tableCellOne', $DSP->qspan('', $LANG->line('sort_order')));

        $r .= $DSP->table_qcell('tableCellTwo',   $DSP->input_select_header('sort_order')
												  .$order_options
									              .$DSP->input_select_footer());                
        $r .= $DSP->tr_c();

        $r .= $DSP->tr();                
        $r .= $DSP->table_qcell('tableCellOne', $DSP->qspan('', $LANG->line('colour')));
        $r .= $DSP->table_qcell('tableCellTwo', $DSP->input_text('hex_colour', $hex_colour, 8, 8, 'textfield', '').
			"<em>e.g. #000000</em>");                
        $r .= $DSP->tr_c();

        $r .= $DSP->tr();                
        $r .= $DSP->table_qcell('tableCellOne', $DSP->qspan('', '&nbsp;', '', 'top'));

		if (sizeof($boolean_room_values) > 0) 
		{
			foreach ($boolean_room_values as $field_name => $value)
			{
				$checked = ($value == 'yes' ? 'checked' : '');
				$long_label = $this->boolean_room_attributes[$field_name]['long'];
		        $r .= $DSP->table_qcell('tableCellTwo',  $DSP->input_checkbox($field_name, '1', $checked) . " " .$long_label);
			}
		}

        $r .= $DSP->tr_c();
		

        $r .= $DSP->table_c();       

        // ------------------------------------------------------- 
        //  Submit Button Text - Add/Update 
        // ------------------------------------------------------- 
         
        if ($room_name != '') 
        { 
            $r .= $DSP->qdiv('itemWrapper', BR.$DSP->input_submit($LANG->line('update_room')));     
        } 
        else 
        { 
            $r .= $DSP->qdiv('itemWrapper', BR.$DSP->input_submit($LANG->line('add_room')));   
        } 
         
        // ------------------------------------------------------- 
        //  Close Form 
        // ------------------------------------------------------- 
         
           $r .= $DSP->form_c(); 

        $DSP->body .= $r;   
    } 
    // END 
     

    // ------------------------- 
    //  Add/Modify Location Form 
    // ------------------------- 
     
    function modify_location($msg='') 
    { 
        global $DSP, $LANG, $DB, $IN; 
         
        // ------------------------------------------------------- 
        //  If Modfying Existing Location, Retrieve data
        // ------------------------------------------------------- 
         
        if ( ! $IN->GBL('location_id')) 
        { 
            $location_name = ''; 
        } 
        else 
        { 
			$sql = "SELECT * FROM exp_ncb_room_locations WHERE location_id = '".$IN->GBL('location_id')."'";
            $query = $DB->query($sql); 
                                 
//			print("query: $sql<br/>");//TMP
								 
            if ($query->num_rows == 0) 
            { 
                $DSP->body .= $DSP->error_message($LANG->line('invalid_location_id'));         
                return; 
            } 
             
            $location_name = $query->row['location_name']; 
       } 
         
        // ------------------------------------------------------- 
        //  HTML Title and Navigation Crumblinks 
        // ------------------------------------------------------- 
         
        $DSP->title = $LANG->line('ncb_rooms_module_name'); 
        $DSP->crumb = $DSP->anchor(BASE. 
                                   AMP.'C=modules'. 
                                   AMP.'M=ncb_rooms', 
                                   $LANG->line('ncb_rooms_module_name'));        
                                    
        $DSP->crumb .= $DSP->crumb_item(($location_name != '') ? $LANG->line('update_location') : $LANG->line('add_location')); 
         
         
        // ------------------------------------------------------- 
        //  Page Heading and Success Message, if any 
        // ------------------------------------------------------- 
         
        $r = $DSP->heading(($location_name != '') ? $LANG->line('update_location') : $LANG->line('add_location')); 
         
        if ($msg != '') 
        { 
            $r .= $DSP->qdiv('success', $msg).BR; 
        } 
         
        // ------------------------------------------------------- 
        // Declare Form 
        // ------------------------------------------------------- 
         
        $r .= $DSP->form('C=modules'.AMP.'M=ncb_rooms'.AMP.'P=update_location', 'target'); 
         
        // ------------------------------------------------------- 
        //  Modifying Existing Location, Hidden Form Field for ID 
        // ------------------------------------------------------- 
         
        if ($location_name != '') 
        { 
            $r .= $DSP->input_hidden('location_id', $IN->GBL('location_id')); 
        } 
         
        // ------------------------------------------------------- 
        //  Table For Textarea 
        // ------------------------------------------------------- 
         
        $r .= $DSP->table('tableBorder', '0', '0', '400');

        $r .= $DSP->tr();                
        $r .= $DSP->table_qcell('tableCellOne', $DSP->qspan('', $LANG->line('location_name')));
        $r .= $DSP->table_qcell('tableCellTwo', $DSP->input_text('location_name', $location_name, 50, 200, 'textfield', '300'));                
        $r .= $DSP->tr_c();

        $r .= $DSP->table_c();       

        // ------------------------------------------------------- 
        //  Submit Button Text - Add/Update 
        // ------------------------------------------------------- 
         
        if ($location_name != '') 
        { 
            $r .= $DSP->qdiv('itemWrapper', BR.$DSP->input_submit($LANG->line('update_location')));     
        } 
        else 
        { 
            $r .= $DSP->qdiv('itemWrapper', BR.$DSP->input_submit($LANG->line('add_location')));   
        } 
         
        // ------------------------------------------------------- 
        //  Close Form 
        // ------------------------------------------------------- 
         
           $r .= $DSP->form_c(); 

        $DSP->body .= $r;   
    } 
    // END modify_location

     
    // ------------------------- 
    // Update/Create Room 
    // ------------------------- 
     
    function update_room() 
    { 
        global $LANG, $DB, $IN, $DSP; 
                
        // ------------------------------------------------------- 
        //  Valid Room Text Received? 
        // ------------------------------------------------------- 
         
        $room_name = (isset($_POST['room_name']) ? trim($_POST['room_name']) : ''); 
        $room_description = (isset($_POST['room_description']) ? trim($_POST['room_description']) : ''); 
        $room_size = (isset($_POST['room_size']) ? trim($_POST['room_size']) : ''); 
        $room_location = (isset($_POST['room_location']) ? trim($_POST['room_location']) : ''); 
        $has_video_conferencing = (isset($_POST['has_video_conferencing']) ? 'yes' : 'no'); 
        $sort_order = $_POST['sort_order'];
        $hex_colour = $_POST['hex_colour'];
		 
        if ($room_name == '') 
        { 
            $DSP->body .= $DSP->error_message($LANG->line('invalid_room_name'));         
            return; 
        } 
         
        // ------------------------------------------------------- 
        //  Insert or Update Depending on Room ID 
        // ------------------------------------------------------- 
        $data = array('room_id'        => '', 
                      'room_name'    => $room_name,
                      'room_description'    => $room_description,
                      'room_size'    => $room_size,
                      'has_video_conferencing'    => $has_video_conferencing,
                      'location_idFK'    => $room_location,
					  'sort_order' => $sort_order,
					  'hex_colour' => $hex_colour,
		  ); 
                  
        if ( ! isset($_POST['room_id'])) 
        { 
            $DB->query($DB->insert_string('exp_ncb_rooms', $data)); 
             
            // --------------------------------------------------- 
            //  Return to Form with Success Message 
            // --------------------------------------------------- 
             
            return $this->ncb_rooms_home($LANG->line('room_added')); 
        } 
        else 
        { 
			$data['room_id'] = $_POST['room_id'];
            $DB->query($DB->update_string('exp_ncb_rooms', $data, "room_id ='".$_POST['room_id']."'"));     
             
            // --------------------------------------------------- 
            //  Return to main menu with Success Message 
            // --------------------------------------------------- 
             
            return $this->ncb_rooms_home($LANG->line('room_updated')); 
        } 
         
    } 
    // END update_room
     

    // ------------------------- 
    // Update/Create Location 
    // ------------------------- 
     
    function update_location() 
    { 
        global $LANG, $DB, $IN, $DSP; 
                
        // ------------------------------------------------------- 
        //  Valid Location name Received? 
        // ------------------------------------------------------- 
         
        $location_name = (isset($_POST['location_name']) ? trim($_POST['location_name']) : ''); 
         
        if ($location_name == '') 
        { 
            $DSP->body .= $DSP->error_message($LANG->line('invalid_location_name'));         
            return; 
        } 
         
        // ------------------------------------------------------- 
        //  Insert or Update Depending on Location ID 
        // ------------------------------------------------------- 
        $data = array('location_id'        => '', 
                      'location_name'    => $location_name,
		  ); 
                  
        if ( ! isset($_POST['location_id'])) 
        { 
            $DB->query($DB->insert_string('exp_ncb_room_locations', $data)); 
             
            // --------------------------------------------------- 
            //  Return to Form with Success Message 
            // --------------------------------------------------- 
             
            return $this->ncb_rooms_home($LANG->line('location_added')); 
        } 
        else 
        { 
			$data['location_id'] = $_POST['location_id'];
            $DB->query($DB->update_string('exp_ncb_room_locations', $data, "location_id ='".$_POST['location_id']."'"));     
             
            // --------------------------------------------------- 
            //  Return to main menu with Success Message 
            // --------------------------------------------------- 
             
            return $this->ncb_rooms_home($LANG->line('location_updated')); 
        } 
         
    } 
    // END update_location

     
    // ------------------------- 
    // Delete Room 
    // ------------------------- 
     
    function delete_room() 
    { 
        global $LANG, $DB, $IN, $DSP; 
         
//        print("<script language=\"javascript\">alert('Ncb_rooms_CP::delete_room');</script>");//TMP 				  

        // ------------------------------------------------------- 
        //  Room ID is required 
        // ------------------------------------------------------- 		 
        if ( ! $IN->GBL('room_id')) 
        { 
            $DSP->body .= $DSP->error_message($LANG->line('invalid_room_id'));         
            return; 
        } 
        else // delete room from DB
        { 
			$sql = "DELETE FROM exp_ncb_rooms WHERE room_id = '".$IN->GBL('room_id')."'";
            $query = $DB->query($sql); 
                  
//        	print("room id: ".$IN->GBL('room_id')."<br/>sql: $sql<br/>");//TMP 				  
				                 
            if ($DB->affected_rows > 0) // delete associated bookings
            {
	            $query = $DB->query("DELETE FROM exp_ncb_room_bookings 
	                                 WHERE room_idFK = '".$IN->GBL('room_id')."'"); 				 
            } 
			else
			{
                $DSP->body .= $DSP->error_message($LANG->line('invalid_room_id'));         
                return; 			
			}
        } 
         
        // ------------------------------------------------------- 
        //  Return to main menu with Success Message 
        // ------------------------------------------------------- 
         
        return $this->ncb_rooms_home($LANG->line('room_deleted'));         
    } 
    // END delete_room


    // ------------------------- 
    // Delete Location 
    // ------------------------- 
     
    function delete_location() 
    { 
        global $LANG, $DB, $IN, $DSP; 
         
//        print("<script language=\"javascript\">alert('Ncb_locations_CP::delete_location');</script>");//TMP 				  

        // ------------------------------------------------------- 
        //  Location ID is required 
        // ------------------------------------------------------- 		 
        if ( ! $IN->GBL('location_id')) 
        { 
            $DSP->body .= $DSP->error_message($LANG->line('invalid_location_id'));         
            return; 
        } 
        else // delete location from DB
        { 
			$sql = "DELETE FROM exp_ncb_room_locations WHERE location_id = '".$IN->GBL('location_id')."'";
            $query = $DB->query($sql); 
                  
//        	print("location id: ".$IN->GBL('location_id')."<br/>sql: $sql<br/>");//TMP 				  
				                 
            if ($DB->affected_rows == 0)
            {
                $DSP->body .= $DSP->error_message($LANG->line('invalid_location_id'));         
                return; 			
            } 
        } 
         
        // ------------------------------------------------------- 
        //  Return to main menu with Success Message 
        // ------------------------------------------------------- 
         
        return $this->ncb_rooms_home($LANG->line('location_deleted'));         
    } 
    // END delete_location


	function get_rooms_count()
	{
		global $DB;
	
		$sql = "SELECT Count(*) as count FROM exp_ncb_rooms";
		$query = $DB->query($sql);

		$count = $query->result[0]['count'];
		
		return $count;		
	}
}

?>